# encoding=utf-8
import datetime

from flask import request

from db.client import cli
from utils.tools import parse_traffic_rate, all_none, parse_uplink_rate
from itertools import groupby
from datetime import date

import numpy as np
import timeFlag_bp

TREND_K = 0.1


class Trend:
    INCREASE = 1
    STABLE = 2
    DECREASE = 3

    def __init__(self):
        raise NotImplemented()

    @staticmethod
    def to_str(trend):
        if trend == Trend.STABLE:
            return 'STABLE'
        elif trend == Trend.INCREASE:
            return 'INCREASE'
        elif trend == Trend.DECREASE:
            return 'DECREASE'
        else:
            return 'INVALID'


def check_trend(k):
    """
    :type k: float
    :param k:
    :return:
    """
    if -TREND_K <= k <= TREND_K:
        return Trend.STABLE
    elif k > TREND_K:
        return Trend.INCREASE
    else:
        return Trend.DECREASE


def build_trend_line(k, b, x_list):
    """
    :type k: float
    :type b: float
    :type x_list: list[float]
    :param k:
    :param b:
    :param x_list:
    :return:
    """
    x1, x2 = min(x_list), max(x_list)
    y1, y2 = round(k * x1 + b, 2), round(k * x2 + b, 2)
    return {
        'x1': x1,
        'y1': y1,
        'x2': x2,
        'y2': y2
    }


def distribution(data, bins_interval):
    bins = list(range(min(data), max(data) + bins_interval, bins_interval))
    hist = np.histogram(data, bins)
    return hist[0]


def linear_fit(x, y):
    x_data = x
    y_data = y
    poly = np.polyfit(x_data, y_data, deg=1)
    return poly[0], poly[1]


def y_diff(data):
    """
    :type data: list[float]
    :param data:
    :return:
    """
    if not data or len(data) == 1:
        return 0

    y = data[1:]
    z = [_y - x for x, _y in zip(data, y)]
    return sum(z)


def check_diff(trend, diff):
    """
    :type trend: int
    :type diff: float
    :param trend:
    :param diff:
    :return:
    """
    return trend == Trend.INCREASE and diff > 0 or trend == Trend.DECREASE and diff < 0


def get_top_k_aaa_user(dp, k):
    """
    :type dp: str
    :type dt: str
    :type st: str
    :type k: float
    :param dp:
    :param dt:
    :param k:
    :return:
    """
    # table_name = "middle_pon_aaa_divide".format(dt)
    res = dict()
    if dp:
        count_sql = "select count(*) as cnt from middle_pon_aaa_divide{} where `分公司` = '{}';".format(
            timeFlag_bp.currentTime, dp)
        # print(k)
        # print(cli.fetchone(count_sql))
        limit = int(cli.fetchone(count_sql)['cnt'] * k)
        # print(limit)
        ds_list_sql = "select sum(downstream) as totaldown from (SELECT `用户ID`, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`, `olt名称` AS olt_name, " \
                      "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率`, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
                      "where `分公司` = '{}' " \
                      "order by `下行流量` desc LIMIT {}) as temp;".format(timeFlag_bp.currentTime, dp, limit)
        ds_sum_sql = "select sum(`下行流量`) as s from middle_pon_aaa_divide{} where `分公司` = '{}';".format(
            timeFlag_bp.currentTime, dp)

        us_list_sql = "select sum(upstream) as totalup from (SELECT `用户ID`, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`,  `olt名称` AS olt_name, " \
                      "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率`, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
                      "where `分公司` = '{}' " \
                      "order by `上行流量` desc LIMIT {}) as temp;".format(timeFlag_bp.currentTime, dp, limit)
        us_sum_sql = "select sum(`上行流量`) as s from middle_pon_aaa_divide{} where `分公司` = '{}';".format(
            timeFlag_bp.currentTime, dp)
    else:
        count_sql = "select count(*) as cnt from middle_pon_aaa_divide{} ;".format(
            timeFlag_bp.currentTime)

        limit = int(cli.fetchone(count_sql)['cnt'] * k)

        ds_list_sql = "select sum(downstream) as totaldown from (SELECT `用户ID`, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`, `olt名称` AS olt_name, " \
                      "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率`, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
                      "order by `下行流量` desc LIMIT {}) as temp;".format(timeFlag_bp.currentTime,limit)
        ds_sum_sql = "select sum(`下行流量`) as s from middle_pon_aaa_divide{} ;".format(timeFlag_bp.currentTime)

        us_list_sql = "select sum(upstream) as totalup from (SELECT `用户ID`, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`,  `olt名称` AS olt_name, " \
                      "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率`, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
                      "order by `上行流量` desc LIMIT {}) as temp;".format(timeFlag_bp.currentTime,limit)
        us_sum_sql = "select sum(`上行流量`) as s from middle_pon_aaa_divide{} ;".format(timeFlag_bp.currentTime)
    #     count_sql = "select count(*) as cnt from middle_pon_aaa_divide{} where `分公司` = '{}';".format(
    #         timeFlag.currentTime, dp)
    #     limit = int(cli.fetchone(count_sql)['cnt'] * k)
    #     ds_list_sql = "SELECT `用户ID`, `上行流量`, `下行流量`, `在线时长`, `分公司`, substring_index(`olt名称`,'_', 1), `olt名称` AS olt_name, " \
    #                   "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率`, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
    #                   "where `分公司` = '{}' order by `下行流量` desc LIMIT {};".format(timeFlag.currentTime, dp, limit)
    #     ds_sum_sql = "select sum(`下行流量`) as s from middle_pon_aaa_divide{} where `分公司` = '{}';".format(timeFlag.currentTime, dp)
    #     us_list_sql = "SELECT id, upstream, downstream, online_time, department_name, station, OLT_name AS olt_name, " \
    #                   "PON_board AS pon_board, PON_port AS pon_port, speed, ONU AS onu FROM `{}` " \
    #                   "where department_name = '{}' " \
    #                   "order by upstream desc LIMIT {};".format(timeFlag.currentTime, dp, limit)
    #     us_sum_sql = "select sum(upstream) as s from `{}` where department_name = '{}';".format(timeFlag.currentTime, dp)
    # # s = cli.fetchall(ds_list_sql)
    # print(s)
    # float(cur.encode("utf-8"))
    # print(ds_list_sql)
    s1 = cli.fetchall(ds_list_sql)[0]['totaldown']
    res['downstream'] = {
        'total_traffic': round(cli.fetchone(ds_sum_sql)['s'], 2),
        'head_traffic': round(s1, 2),
        # 'head_traffic': round(sum(map(lambda x: float(x['downstream'].encode("utf-8")), s)), 2),
        'list': []
    }
    s2 = cli.fetchall(us_list_sql)[0]['totalup']
    res['upstream'] = {
        'total_traffic': round(cli.fetchone(us_sum_sql)['s'], 2),
        'head_traffic': round(s2, 2),
        # 'head_traffic': round(sum(map(lambda x: float(x['upstream'].encode("utf-8")), s)), 2),
        'list': []
    }
    # print(res)
    return res


def head_user_list(dp, k):
    """
    :type department: str
    :type station: str
    :type dt: str
    :type k: float
    :param department:
    :param station:
    :param dt:
    :param k:
    :return:
    """
    res = dict()
    temp = dict()
    if dp:
        count_sql = "select count(*) as cnt from middle_pon_aaa_divide{} where `分公司` = '{}';".format(
            timeFlag_bp.currentTime, dp)
        # print(k)
        # print(cli.fetchone(count_sql))
        limit = int(cli.fetchone(count_sql)['cnt'] * k)
        ds_list_sql = "SELECT `用户ID` as id, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`, `olt名称` AS olt_name, " \
                      "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率` as speed, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
                      "where `分公司` = '{}' " \
                      "order by `下行流量` desc LIMIT {};".format(timeFlag_bp.currentTime, dp, limit)

        us_list_sql = "SELECT `用户ID` as id, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`,  `olt名称` AS olt_name, " \
                      "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率` as speed, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
                      "where `分公司` = '{}' " \
                      "order by `上行流量` desc LIMIT {};".format(timeFlag_bp.currentTime, dp, limit)
    # r = get_top_k_aaa_user(department, k)
    else:
        count_sql = "select count(*) as cnt from middle_pon_aaa_divide{} ;".format(
            timeFlag_bp.currentTime)
        # print(k)
        # print(cli.fetchone(count_sql))
        limit = int(cli.fetchone(count_sql)['cnt'] * k)
        ds_list_sql = "SELECT `用户ID` as id, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`, `olt名称` AS olt_name, " \
                      "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率` as speed, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
                      "order by `下行流量` desc LIMIT {};".format(timeFlag_bp.currentTime, limit)

        us_list_sql = "SELECT `用户ID` as id, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`,  `olt名称` AS olt_name, " \
                      "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率` as speed, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
                      "order by `上行流量` desc LIMIT {};".format(timeFlag_bp.currentTime, limit)
    # r = get_top_k_aaa_user(department, k)
    #     count_sql = "select count(*) as cnt from middle_pon_aaa_divide{} where `分公司` = '{}';".format(
    #         timeFlag.currentTime, dp)
    #     limit = int(cli.fetchone(count_sql)['cnt'] * k)
    #     ds_list_sql = "SELECT `用户ID`, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`, `olt名称` AS olt_name, " \
    #                   "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率` as speed , `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
    #                   "where `分公司` = '{}' " \
    #                   "order by `下行流量` desc LIMIT {}) as temp;".format(timeFlag.currentTime, dp, limit)
    #
    #     us_list_sql = "SELECT `用户ID`, `上行流量` as upstream, `下行流量` as downstream, `在线时长`, `分公司`,  `olt名称` AS olt_name, " \
    #                   "`PON板号` AS pon_board, `PON口号` AS pon_port, `速率` as speed, `ONU设备型号` AS onu FROM middle_pon_aaa_divide{} " \
    #                   "where `分公司` = '{}' " \
    #                   "order by `上行流量` desc LIMIT {}) as temp;".format(timeFlag.currentTime, dp, limit)
    # # r = get_top_k_aaa_user(department, k)

    s1 = cli.fetchall(ds_list_sql)
    s2 = cli.fetchall(us_list_sql)
    temp['downstream'] = {
        'list': s1
    }
    temp['upstream'] = {
        'list': s2
    }
    res = {
        'upstream': format_user_list(temp['upstream']['list']),
        'downstream': format_user_list(temp['downstream']['list']),
        'upstream_count': count_by_speed(temp['upstream']['list']),
        'downstream_count': count_by_speed(temp['downstream']['list'])
    }
    return res


def count_by_speed(user_list):
    sp = list(map(lambda e: e['speed'], user_list))
    sp.sort()
    r = {}
    s = groupby(sp, key=lambda e: e)
    for k, v in s:
        r[k] = len(list(v))
    return r


def format_user_list(rs):
    """
    :type rs: list[dict]
    :param rs:
    :return:
    """
    r = []
    x = groupby(rs, key=lambda e: e['olt_name'])
    for olt, _x in x:
        y = groupby(_x, key=lambda e: e['pon_board'])
        for pb, _y in y:
            z = groupby(_y, key=lambda e: e['pon_port'])
            for pp, _z in z:
                r.append({
                    'olt_name': olt,
                    'pon_board': pb,
                    'pon_port': pp,
                    'user_count': len(list(_z))
                })
    r = sorted(r, key=lambda e: e['user_count'], reverse=True)
    return r


def get_pon_port_traffic_statistics(department_name, interval):
    """
    :type city_name: str,
    :type department_name: str
    :type interval: int
    :param city_name:
    :param department_name:
    :return:
    """
    if department_name:
        sql = "SELECT `流入均值` as input_average_traffic, `流入峰值` as input_peak_traffic, " \
              "`流出均值` as output_average_traffic,`流出峰值` as output_peak_traffic " \
              "FROM base_pon_traffic{} " \
              "WHERE `分公司` = '{}';".format(timeFlag_bp.currentTime, department_name)
    else:
        sql = "SELECT `流入均值` as input_average_traffic, `流入峰值` as input_peak_traffic, " \
              "`流出均值` as output_average_traffic,`流出峰值` as output_peak_traffic " \
              "FROM base_pon_traffic{} ".format(timeFlag_bp.currentTime)
    # elif city_name:
    #     sql = "SELECT input_average_traffic, input_peak_traffic, " \
    #           "output_average_traffic, output_peak_traffic " \
    #           "FROM pon_traffic_statistics_csv " \
    #           "WHERE city_name = '{}';".format(city_name)
    # else:
    #     sql = ''
    r = cli.fetchall(sql)
    f = {
        'in_avg': map(lambda x: parse_traffic_rate(x['input_average_traffic']), r),
        'in_peak': map(lambda x: parse_traffic_rate(x['input_peak_traffic']), r),
        'out_avg': map(lambda x: parse_traffic_rate(x['output_average_traffic']), r),
        'out_peak': map(lambda x: parse_traffic_rate(x['output_peak_traffic']), r)
    }
    res = {}
    for k, v in f.items():
        res[k] = {
            'y': list(distribution(v, interval))
        }
        res[k]['x'] = range(0, len(res[k]['y']) * interval, interval)
    return res


def get_uplink_port_traffic_statistics(department_name, interval):
    """
    :type city_name: str,
    :type department_name: str
    :type interval: int
    :param city_name:
    :param department_name:
    :return:
    """
    if department_name:
        sql = "SELECT `上联流入流量均值` as input_average_traffic, `上联流入流量峰值` as input_peak_traffic, " \
              "`上联流出流量均值` as output_average_traffic,`上联流出流量峰值` as output_peak_traffic " \
              "FROM middle_OLTMassage{} " \
              "WHERE `分公司` = '{}';".format(timeFlag_bp.currentTime, department_name)
    else:
        sql = "SELECT `上联流入流量均值` as input_average_traffic, `上联流入流量峰值` as input_peak_traffic, " \
              "`上联流出流量均值` as output_average_traffic,`上联流出流量峰值` as output_peak_traffic " \
              "FROM middle_OLTMassage{} ".format(timeFlag_bp.currentTime)
    # elif city_name:
    #     sql = "SELECT input_average_traffic, input_peak_traffic, " \
    #           "output_average_traffic, output_peak_traffic " \
    #           "FROM pon_traffic_statistics_csv " \
    #           "WHERE city_name = '{}';".format(city_name)
    # else:
    #     sql = ''
    r = cli.fetchall(sql)
    f = {
        'in_avg': map(lambda x: parse_uplink_rate(x['input_average_traffic']), r),
        'in_peak': map(lambda x: parse_uplink_rate(x['input_peak_traffic']), r),
        'out_avg': map(lambda x: parse_uplink_rate(x['output_average_traffic']), r),
        'out_peak': map(lambda x: parse_uplink_rate(x['output_peak_traffic']), r)
    }
    res = {}
    for k, v in f.items():
        res[k] = {
            'y': list(distribution(v, interval))
        }
        res[k]['x'] = range(0, len(res[k]['y']) * interval, interval)
    return res


# def get_pon_trend(department_name, station, tag):
#     """
#     :type city_name: str
#     :type department_name: str
#     :type station: str
#     :type olt_name: str
#     :param city_name:
#     :param department_name:
#     :param station:
#     :param olt_name:
#     :return:
#     """
#     # if department_name and station :
#     #     sql = "SELECT `分公司` as department_name, substring_index(`olt名称`,'_', 1) as station, `olt名称` as olt_name, `流入均值` as input_avg, `流入峰值` as input_peak, " \
#     #           "`流出均值` as output_avg, `流出峰值` as output_peak, `PON板号` as pon_board, `PON口号` as pon_port, `采集时间` as date FROM base_pon_traffic{}" \
#     #           "WHERE `分公司` = '{}' " \
#     #           "AND substring_index(`olt名称`,'_', 1) = '{}' " \
#     #           "ORDER BY `分公司`, substring_index(`olt名称`,'_', 1), `olt名称`, `PON板号`, `PON口号`, `采集时间`;".format(timeFlag.currentTime, department_name,station)
#     if department_name and station:
#         sql = "SELECT `分公司` as department_name, substring_index(`olt名称`,'_', 1) as station, `olt名称` as olt_name, `流入均值` as input_avg, `流入峰值` as input_peak, " \
#               "`流出均值` as output_avg, `流出峰值` as output_peak, `PON板号` as pon_board, `PON口号` as  pon_port, `采集时间` as `date` FROM base_pon_traffic{} " \
#               "WHERE `分公司` = '{}' " \
#               "AND substring_index(`olt名称`,'_', 1) = '{}'" \
#               "ORDER BY `分公司`, substring_index(`olt名称`,'_', 1), `olt名称`, `PON板号`, `PON口号`, `采集时间`;".format(
#             timeFlag_bp.currentTime, department_name, station)
#     elif department_name:
#         sql = "SELECT `分公司` as department_name, substring_index(`olt名称`,'_', 1) as station, `olt名称` as olt_name, `流入均值` as input_avg, `流入峰值` as input_peak," \
#               "`流出均值` as output_avg, `流出峰值` as output_peak, `PON板号` as pon_board, `PON口号` as pon_port, `采集时间` as `date` FROM base_pon_traffic{} " \
#               "WHERE `分公司` = '{}'" \
#               "ORDER BY `分公司`, substring_index(`olt名称`,'_', 1), `olt名称`, `PON板号`, `PON口号`, `采集时间`;".format(
#             timeFlag_bp.currentTime, department_name)
#     else:
#         sql = "SELECT `分公司` as department_name, substring_index(`olt名称`,'_', 1) as station, `olt名称` as olt_name, `流入均值` as input_avg, `流入峰值` as input_peak," \
#               "`流出均值` as output_avg, `流出峰值` as output_peak, `PON板号` as pon_board, `PON口号` as pon_port, `采集时间` as `date` FROM base_pon_traffic{} " \
#               "ORDER BY `分公司`, substring_index(`olt名称`,'_', 1), `olt名称`, `PON板号`, `PON口号`, `采集时间`;".format(
#             timeFlag_bp.currentTime)
#         # return dict(success=False, msg='invalid parameters.')
#     r = cli.fetchall(sql)
#     z = groupby(r, lambda e: e['department_name'])
#     res = []
#     for department, stations in z:
#         for station, olts in groupby(stations, lambda e: e['station']):
#             for olt, boards in groupby(olts, lambda e: e['olt_name']):
#                 for board, ports in groupby(boards, lambda e: e['pon_board']):
#                     for p, records in groupby(ports, lambda e: e['pon_port']):
#                         rs = list(records)
#                         # x = map(lambda e: e['date'], p)
#                         x = [i for i in range(1, len(rs) + 1)]
#
#                         y = []
#                         temp = map(lambda e: e['{}_avg'.format(tag)], rs)
#                         for item in temp:
#                             item = float(item[:-4])
#                             y.append(item)
#
#                         # y = map(lambda e: e['{}_avg'.format(tag)], rs)
#                         # y=[temp]
#                         # print(x)
#                         # print(y)
#                         k, b = linear_fit(x, y)
#                         trend = check_trend(k)
#                         tl = build_trend_line(k, b, x)
#                         tl.update({'x1': date.isoformat(rs[0]['date']), 'x2': date.isoformat(rs[-1]['date'])})
#
#                         m = {
#                             'department': department,
#                             'station': station,
#                             'olt': olt,
#                             'pon_board': board,
#                             'pon_port': p,
#                             'type': Trend.to_str(trend),
#                             'y_diff': check_diff(trend, y_diff(y)),
#                             'traffic_tag': tag,
#                             'samples': {
#                                 'x': map(lambda e: date.isoformat(e['date']), rs),
#                                 'avg': y,
#                                 'peak': map(lambda e: e['{}_peak'.format(tag)], rs)
#                             },
#                             'trend_line': tl
#                         }
#                         res.append(m)
#     return res
def get_pon_trend(city_name, department_name, station, olt_name, tag):
    """
    :type city_name: str
    :type department_name: str
    :type station: str
    :type olt_name: str
    :param city_name:
    :param department_name:
    :param station:
    :param olt_name:
    :return:
    """
    if city_name and department_name and station and olt_name:
        sql = "SELECT department_name, station, olt_name, input_avg, input_peak, " \
              "output_avg, output_peak, pon_board, pon_port, date FROM pon_traffic_time_line " \
              "WHERE department_name = '{}' " \
              "AND station = '{}' " \
              "AND olt_name = '{}'" \
              "ORDER BY department_name, station, olt_name, pon_board, pon_port, date;".format(department_name,
                                                                                               station,
                                                                                               olt_name)
    elif city_name and department_name and station:
        sql = "SELECT department_name, station, olt_name, input_avg, input_peak, " \
              "output_avg, output_peak, pon_board, pon_port, date FROM pon_traffic_time_line " \
              "WHERE department_name = '{}' " \
              "AND station = '{}'" \
              "ORDER BY department_name, station, olt_name, pon_board, pon_port, date;".format(department_name, station)
    elif city_name and department_name:
        sql = "SELECT department_name, station, olt_name, input_avg, input_peak, " \
              "output_avg, output_peak, pon_board, pon_port, date FROM pon_traffic_time_line " \
              "WHERE department_name = '{}'" \
              "ORDER BY department_name, station, olt_name, pon_board, pon_port, date;".format(department_name)
    else:
        return dict(success=False, msg='invalid parameters.')
    r = cli.fetchall(sql)
    z = groupby(r, lambda e: e['department_name'])
    res = []
    for department, stations in z:
        for station, olts in groupby(stations, lambda e: e['station']):
            for olt, boards in groupby(olts, lambda e: e['olt_name']):
                for board, ports in groupby(boards, lambda e: e['pon_board']):
                    for p, records in groupby(ports, lambda e: e['pon_port']):
                        rs = list(records)
                        # x = map(lambda e: e['date'], p)
                        x = [i for i in range(1, len(rs) + 1)]
                        y = map(lambda e: e['{}_avg'.format(tag)], rs)
                        k, b = linear_fit(x, y)
                        trend = check_trend(k)
                        tl = build_trend_line(k, b, x)
                        tl.update({'x1': date.isoformat(rs[0]['date']), 'x2': date.isoformat(rs[-1]['date'])})
                        m = {
                            'department': department,
                            'station': station,
                            'olt': olt,
                            'pon_board': board,
                            'pon_port': p,
                            'type': Trend.to_str(trend),
                            'y_diff': check_diff(trend, y_diff(y)),
                            'traffic_tag': tag,
                            'samples': {
                                'x': map(lambda e: date.isoformat(e['date']), rs),
                                'avg': y,
                                'peak': map(lambda e: e['{}_peak'.format(tag)], rs)
                            },
                            'trend_line': tl
                        }
                        res.append(m)
    return res


def getTime(note):
    if all_none([note]):
        return dict(success=False, msg='query parameter invalid.')

    sql = "SELECT `导入日期` as times FROM log_information where `注释` = '{}';".format(note.encode('utf-8'))
    res = cli.fetchone(sql)['times']
    temp = '_' + res[0:10]
    result = temp.replace("-", "_")
    return result
    # return dict(success=True, data=result)


if __name__ == '__main__':
    # r = get_pon_trend('tianjin', '南开分公司', 'NKKYD', 'NKKYD_HW_OLT02', 'input')
    # print r
    r = head_user_list('南开分公司', 'NKKYD', '20190102', 0.1)
    print r
